#include "xread_task.h"
#include <iostream>

bool XReadTask::init(const std::string &fileName)
{
    if (fileName.empty()) {
        return false;
    }
    ifs_.open(fileName, std::ios::binary);
    if (!ifs_) {
        std::cerr << "open file:" << fileName << " failed!" << std::endl;
        return false;
    }

    ifs_.seekg(0, std::ios::end);
    dataBytes_ = ifs_.tellg();
    ifs_.seekg(0, std::ios::beg);
    std::cout << "file size:" << dataBytes_ << std::endl;

    return true;
}

void XReadTask::handle()
{
    while (!isExit_) {
        if (ifs_.eof()) {
            break;
        }
        auto data = XData::make_data(memPool_);
        int dataSize = 1024;
        void *buf = data->alloc(dataSize);
        ifs_.read((char*)buf, dataSize);
        if (ifs_.gcount() <= 0) {
            break;
        }
        data->setSize(ifs_.gcount());
        if (ifs_.eof()) {
            data->setEnd(true);
        }
        if (next_) {
            next_->push(data);
        }
    }
    ifs_.close();
    std::cout << "end thread XReadTask::handle" << std::endl;
}